package com.atguigu.gmall.web.controller;

import com.atguigu.gmall.item.feign.ItemFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Map;

@Controller
@RequestMapping("/page/item")
public class ItemController {

    @Autowired
    private ItemFeign itemFeign;
    @Autowired
    private TemplateEngine templateEngine;

    @GetMapping
    public String item(Long skuId, Model model){
        //远程调用item微服务
        Map skuInfo = itemFeign.getSkuInfo(skuId);

        //2 将数据存入请求域中
        model.addAllAttributes(skuInfo);

        //3 返回页面
        return "item";
    }

    /**
     * 为每个商品生成静态页面
     * @param skuId
     * @return
     */
    @GetMapping("/createHtml")
    @ResponseBody
    public String createHtml(Long skuId) throws FileNotFoundException {
        try{
            //远程调用item微服务
            Map skuInfo = itemFeign.getSkuInfo(skuId);

            //声明一个输出流
            File file = new File("D:\\java0828",skuId + ".html");
            PrintWriter printWriter = new PrintWriter(file,"UTF-8");

            //封装数据
            Context context = new Context();
            context.setVariables(skuInfo);

            //生成静态页面
            templateEngine.process("itemTemplate",context,printWriter);
            printWriter.close();

            return "生成成功";
        }catch (Exception e){

        }
        return "生成失败";
    }
}
